<?php

namespace App\Http\Controllers;

use App\Models\Role;
use App\Models\User;
use Auth;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class RoleController extends Controller
{
    public function index()
    {
        return response()->json(Role::all(), Response::HTTP_OK, [], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }

    public function set(Request $request)
    {
        if ($request->has('user_id') && Auth::user()->id == 1) {
            $role = Role::whereName(Role::OWNER)->first();

            $user = User::find($request->get('user_id'));

            $user->attachRole($role);
        }

        return response()->json(Role::where('name', Role::OWNER)->first()->users, Response::HTTP_OK, [], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }

    public function create()
    {
        try {
            Role::create([
                'name'         => Role::OWNER,
                'display_name' => Role::OWNER,
                'description'  => 'owner',
            ]);
        } catch (QueryException $e) {
            dump($e->getMessage());
        }
    }
}
